/**
 * @author:linjiye
 * @date: 2024/12/25
 * @desc:
 **/

import {StyleSheet, Text, TextInput, TouchableOpacity, View, Image, ScrollView} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import {FcView} from "@/components/FcView";
import PageFormBtn from "@/components/PageFormBtn";
import TabCard from "@/components/TabCard";
import FormTitle from "@/components/FormTitle";
import FcButton from "@/components/FcButton";
import {aiOriginalityData} from "@/utils/data"
import {
    Flex,
    Button,
    List,
    Modal,
    Provider,
    Switch,
    Toast,
    WhiteSpace,
    WingBlank,
} from "@ant-design/react-native";
import RequiredIcon from "@/components/RequiredIcon";
import {LinearGradient} from "expo-linear-gradient";
import Slider from '@react-native-community/slider';
import FcSlider from "@/components/FcSlider";
import Animated, {useAnimatedRef} from "react-native-reanimated";
import FcModal from "@/components/FcModal";
import {useGetGroupTemplateListQuery, useGetTemplateListQuery} from "@/store/api/aiOriginality/aiOriginalityApi";
import {useDispatch, useSelector} from "react-redux";
import {set_SYZLParams} from "@/store/reducer/aiOriginality/aiOriginalitySlice";
import useSetStorage from "@/hooks/useSetStorage";
import useGetStorage from "@/hooks/useGetStorage";
import {produce} from "immer";

type Props = {}

const SdsrPage = ({ onGetParams}: Props) => {
    const dispatch = useDispatch();
    const storageData = useSelector(state => state.aiOriginality.storageData1)
    const [list, setList] = useState([])
    const [bigMenuId, setBigMenuId] = useState('')
    const [bigMenuIndex, setBigMenuIndex] = useState(0)
    const [smallMenu, setSmallMenu] = useState([])
    const [smallMenuId, setSmallMenuId] = useState('')
    const [smallMenuIndex, setSmallMenuIndex] = useState(0)
    const [formList, setFormList] = useState([])
    const [FcSliderZSVal, setFcSliderZSVal] = useState(100)
    const [FcSliderPSVal, setFcSliderPSVal] = useState(1)
    const [isHotKeyword, setIsHotKeyword] = useState(false)
    const [hotKeywordList, setHotKeywordList] = useState([])
    const [wordsNum, setWordNum] = useState(null)
    const [params, setParams] = useState({
        vars: [],
        reqIndex: 1,
        disable: true,
        wordsNum:100,
        templateId: ''
    })

    const p = useSelector(state => state.aiOriginality.SYZLParams)

    const {data,isSuccess} = useGetGroupTemplateListQuery?.({
        promptCate: 7,
        versionType: 1
    })


    const [originalityStoryData, setOriginalityStoryData] = useState({})
    const [originalityStoryData1, setOriginalityStoryData1] = useState({})
    useEffect(() => {
        useGetStorage('originalityStoryData1').then((res) => {
            console.log(res,'res---');
            if (res) {
                setBigMenuIndex(res?.selectBigMenuIndex)
                setFcSliderPSVal(res?.FcSliderPSVal)
                setOriginalityStoryData(res)
                setOriginalityStoryData1(res)
            }

        })
        console.log(storageData,'---00');
        // if (storageData) {
        //     setBigMenuIndex(storageData?.selectBigMenuIndex)
        //     setFcSliderPSVal(storageData?.FcSliderPSVal)
        //     setOriginalityStoryData(storageData)
        //     setOriginalityStoryData1(storageData)
        // }

        onGetParams(params)
    }, []);

    useEffect(() => {
        if (originalityStoryData1?.list?.length > 0) handleBigMenu1(originalityStoryData1.list[originalityStoryData1?.selectBigMenuIndex], originalityStoryData1?.selectBigMenuIndex)
    }, [originalityStoryData1]);



    // useEffect(() => {
    //     if(data&&data?.code=== 200){
    //         console.log(data,'------------');
    //         // list?.forEach(item => {
    //         //     console.log(item.name);
    //         //     let arr = []
    //         //     data?.result?.forEach(i => {
    //         //         if(i.tag === item.name) arr.push(i)
    //         //     })
    //         //     console.log(arr);
    //         //     item.list = arr
    //         // })
    //         // console.log(result);
    //
    //         let list = data.result || []
    //
    //         setList(list)
    //         setBigMenuId(list[0].label)
    //         setSmallMenu(list[0].list)
    //     }
    //
    //     // onGetParams(params)
    // },[isSuccess,data])

    // useEffect(() => {
    //     handleBigMenu(list[0])
    //     onGetParams(params)
    // }, [list]);


    const handleSetParams = () => {
        useGetStorage('originalityStoryData').then((res) => {
            if (res) {
                let selectSmallMenuIndex = res.list[res.selectBigMenuIndex].selectSmallMenuIndex
                let smallMenuId = res.list[res.selectBigMenuIndex].list[selectSmallMenuIndex].id
                let FcSliderZSVal = res.list[res.selectBigMenuIndex].list[selectSmallMenuIndex].FcSliderZSVal
                let FcSliderPSVal = res.FcSliderPSVal

                dispatch(set_SYZLParams({
                    ...p,
                    articlesNum: FcSliderPSVal,
                    wordsNum: FcSliderZSVal,
                    templateId: smallMenuId
                }))

                setParams(p)
                onGetParams(p)
            }
        })
    }

    function handleBigMenu1(item, index) {
        console.log(item, index);
        setBigMenuId(item.id)
        setBigMenuIndex(index)
        // const newData = produce(originalityStoryData, draft => {
        //     draft.selectBigMenuIndex=index
        // });
        let newData = {...originalityStoryData}
        newData.selectBigMenuIndex = index
        setOriginalityStoryData(newData);
        // dispatch(set_storageData(newData));
        // console.log(newData);
        useSetStorage('originalityStoryData1', newData).then((res) => {
            // console.log(res,'res---');
            if (res.code === 200) {
                handleSetParams()
                useGetStorage('originalityStoryData1').then((res) => {
                    if (res) {
                        setOriginalityStoryData(res)

                        handleSmallMenu1(res.list[index].list[item.selectSmallMenuIndex], res.list[index].selectSmallMenuIndex)
                    }
                })

            }
        })


    }

    function handleSmallMenu1(item, index) {
        setSmallMenuId(item.id)
        setSmallMenuIndex(index)
        // setFcSliderZSVal(item.fieldMin * 1)
        // setFormList(item.formList)

        // console.log(item, 'item.wordsNum');
        if (item.wordsNum) {
            setWordNum(item.wordsNum)
            setFcSliderZSVal(item.FcSliderZSVal)
        }

        useGetStorage('originalityStoryData1').then((res) => {
            if (res) {
                const newData = produce(res, draft => {
                    draft.list[res.selectBigMenuIndex].selectSmallMenuIndex = index
                })

                setOriginalityStoryData(newData);
                // dispatch(set_storageData(newData));
                useSetStorage('originalityStoryData1', newData)
                handleSetParams()
            }
        })
    }

    const handleBigMenu = (val: { label?: any; id: any; list: any; }) => {
        console.log(val,'-111--');
        setBigMenuId(val.label)
        setSmallMenu(val.list)
        if (val?.list?.length) handleSmallMenu(val.list[0])
    }

    const handleSmallMenu = (val) => {
        let formList = val.vars ? JSON.parse(val.vars) : []
        console.log(formList, 'setFormList==');
        let wordsNum = formList.find(item => item.label == '字数')
        formList = formList.filter(item => item.label != '字数')
        console.log(wordsNum, '----');
        setWordNum(wordsNum)
        if (wordsNum) {
            setFcSliderZSVal(wordsNum.fieldMin * 1)
        }
        setSmallMenuId(val.id)
        setFormList(formList)
        handleSetParams()
    }

    function setFcZSSlider(val) {
        setFcSliderZSVal(val)
        useGetStorage('originalityStoryData1').then((res) => {
            if (res) {
                const newData = produce(res, draft => {
                    draft.list[res.selectBigMenuIndex].list[draft.list[res.selectBigMenuIndex].selectSmallMenuIndex].FcSliderZSVal = val;
                });

                setOriginalityStoryData(newData);
                // dispatch(set_storageData(newData));
                useSetStorage('originalityStoryData1', newData)
                handleSetParams()
            }
        })
    }

    const handleChange = (val, index) => {
        formList[index].value = val
        // console.log(formList, val, index);
        setFormList(formList)
        handleSetParams()
    }

    const handleHotKeyword = () => {
        setIsHotKeyword(true)
    }

    const handleFcZSSlider = (val) => {
        setFcSliderZSVal(val)
        handleSetParams()
    }

    // const handleFcPSSlider = (val) => {
    //     setFcSliderPSVal(val)
    //     handleSetParams()
    // }

    const handleFcPSSlider = (val) => {
        setFcSliderPSVal(val)
        // handleSetParams()
        useGetStorage('originalityStoryData1').then((res) => {
            if (res) {

                const newData = produce(res, draft => {
                    draft.FcSliderPSVal = val;
                });

                setOriginalityStoryData(newData);
                // dispatch(set_storageData(newData));
                useSetStorage('originalityStoryData1', newData)
                handleSetParams()
            }
        })
    }

    const getColor = (val: string | number) => {
        switch (val) {
            case 0:
                return '#F8405F'
            case 1:
                return '#EE7B53'
            case 2:
                return '#FCA853'
            default:
                return 'rgba(0, 0, 0, 0.9)'
        }
        return 'index' + val + 1
    }



    // @ts-ignore
    // @ts-ignore
    // @ts-ignore
    return (
        <FcView style={styles.container}>
            {originalityStoryData?.list?.length > 0 &&
                <>
                    <FormTitle isLeftIcon style={{paddingHorizontal: 16}} title='选版发布渠道'/>
                    <Flex wrap='wrap' style={styles.big_menu}>
                        {originalityStoryData?.list?.map((item, index) =>
                            <View style={styles.big_menu_item_box}>
                                <FcButton
                                    key={index}
                                    onClick={() => handleBigMenu1(item, index)}
                                    type={bigMenuIndex === index ? 'txtBK' : 'default'}
                                    style={[styles.big_menu_item]}
                                    itemStyle={{width: '100%', height: '100%'}}
                                    textName={item.name} borderWidth={1}></FcButton>
                            </View>
                        )}
                    </Flex>
                    <View style={styles.small_menu}></View>
                    <Flex wrap='wrap'>
                        {originalityStoryData?.list[bigMenuIndex]?.list?.map((item, index) =>
                                <Text key={index} onPress={() => handleSmallMenu1(item, index)}
                                      style={[styles.small_menu_item, smallMenuIndex === index && styles.small_menu_active]}
                                >
                                    {item.styleFirstCate}
                                </Text>
                            // <FcButton
                            //     key={index} onClick={() => handleSmallMenu(item)}
                            //     style={[styles.small_menu_item, smallMenuId === item.id && styles.small_menu_active]}
                            //     itemStyle={{width: '100%', height: '100%', borderRadius: 8}}
                            //     textName={item.styleFirstCate}></FcButton>
                        )}
                    </Flex>
                    <View style={{paddingHorizontal: 12}}>
                        {/*<FormTitle title='手动输入资料' isLeftIcon/>*/}

                        {/*{originalityStoryData?.list[bigMenuIndex]?.list[smallMenuIndex]?.formList?.map((item, index) =>*/}
                        {/*    <>*/}
                        {/*        {item.label != '热搜词' &&*/}
                        {/*            <View style={styles.input_wrap} key={index}>*/}
                        {/*                <Text style={styles.input_label}>{item.label} {item.required &&*/}
                        {/*                    <RequiredIcon/>}:</Text>*/}
                        {/*                <TextInput*/}
                        {/*                    value={item.value}*/}
                        {/*                    style={styles.input_val}*/}
                        {/*                    placeholder={item.placeholder}*/}
                        {/*                    placeholderTextColor={'rgba(0, 0, 0, 0.3)'}*/}
                        {/*                    onChangeText={(text) => setText(text, index)}*/}
                        {/*                ></TextInput>*/}
                        {/*            </View>*/}
                        {/*        }*/}
                        {/*    </>*/}
                        {/*)}*/}


                        {/*<View style={styles.input_wrap}>*/}
                        {/*  <Text style={styles.input_label}>热搜词 :</Text>*/}
                        {/*  <TextInput style={styles.input_val} placeholder='如“自填或选择抖音热点”'></TextInput>*/}
                        {/*  <TouchableOpacity onPress={handleHotKeyword}>*/}
                        {/*    <Text style={{ fontFamily: 'FcIconFont',fontSize: 20,color: 'black',marginLeft: 10 }}>&#xe643;</Text>*/}
                        {/*  </TouchableOpacity>*/}
                        {/*</View>*/}


                        {wordsNum &&
                            <>
                                <FormTitle title='单篇字数'
                                           isLeftIcon
                                           style={{marginBottom: 8, marginTop: 4}}
                                           right={
                                               <View style={styles.slider_wrap}>
                                                   <TextInput style={styles.slider_input}
                                                              value={FcSliderZSVal + ''}
                                                              onChangeText={setFcZSSlider}></TextInput>
                                                   <Text style={styles.slider_txt}>个</Text>
                                               </View>
                                           }/>
                                <FcSlider value={FcSliderZSVal} showMinMax min={wordsNum.fieldMin * 1}
                                          max={wordsNum.fieldMax * 1} onFcSlider={setFcZSSlider}/>
                            </>
                        }

                        <FormTitle title='输出篇数'
                                   isLeftIcon
                                   style={{marginBottom: 8, paddingTop: 32}}
                                   right={
                                       <View style={styles.slider_wrap}>
                                           <TextInput style={styles.slider_input}
                                                      value={FcSliderPSVal + ''}></TextInput>
                                           <Text style={styles.slider_txt}>个</Text>
                                       </View>
                                   }/>
                        <FcSlider value={FcSliderPSVal} min={1} max={10} showMinMax onFcSlider={handleFcPSSlider}/>
                    </View>
                </>
            }

            <FcModal
                isOpen={isHotKeyword}
                onFcModalClose={() => setIsHotKeyword(false)}
                titleText='抖音热搜榜'
                titleDesc='热点时间：2024-10-24 12:00'
                background={
                    <Image style={{width: '100%', height: 226}}
                           source={require('@/assets/images/public/page_bg2.png')}></Image>
                }
            >
                <View style={{paddingVertical: 8}}>
                    {hotKeywordList.map((item, index) => (
                        <TouchableOpacity key={index}>
                            <View style={styles.hotKeyword_wrap}>
                                <View style={styles.hotKeyword_left}>
                                    <Text style={[styles.hotKeyword_index, {color: getColor(index)}]}>{index + 1}</Text>
                                    <Text style={styles.hotKeyword_title} numberOfLines={1}
                                          ellipsizeMode="tail">{item.title}</Text>
                                </View>
                                <View style={styles.hotKeyword_tj}>{item.num}万</View>
                            </View>
                        </TouchableOpacity>
                    ))}
                </View>
            </FcModal>
        </FcView>
    )
}

export default SdsrPage

const styles = StyleSheet.create({
    container: {
        // flex: 1,
        // justifyContent: "center",
        // alignItems: "center",
        backgroundColor: 'white',
        borderBottomLeftRadius: 8,
        borderBottomRightRadius: 8,
        paddingBottom: 16
    },
    big_menu: {
        paddingHorizontal: 8,
        display: "flex",
        flexWrap: "wrap",
        flexDirection: "row",
    },
    big_menu_item_box: {
        width: '33.33%',
        height: 40,
        marginBottom: 8
    },
    big_menu_item: {
        height: 40,
        lineHeight: 40,
        borderRadius: 8,
        marginHorizontal: 4,
        flex: 1,
    },
    small_menu: {
        paddingTop: 20,
        borderStyle: 'dashed',
        borderTopWidth: 1,
        borderColor: 'rgba(0, 0, 0, 0.1)',
        marginHorizontal: 12,
        marginTop: 12
    },
    small_menu_item: {
        paddingHorizontal: 9,
        paddingVertical: 5,
        borderRadius: 20,
        backgroundColor: '#F1F2F4',
        marginHorizontal: 8,
        marginBottom: 8,
        color: '#79797A',
        fontsize: 14,
    },
    small_menu_active: {
        color: '#2856FF',
        backgroundColor: 'rgba(40, 86, 255, 0.1)'
    },
    input_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        height: 56,
        borderRadius: 10,
        paddingHorizontal: 12,
        backgroundColor: '#F1F2F4',
        marginBottom: 16
    },
    input_label: {
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
        flexDirection: 'row',
        alignItems: "center",
        marginRight: 10
    },
    input_val: {
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
        flex: 1,
        height: '100%',
        borderWidth: 0, // 去掉边框
        outlineWidth: 0, // 去掉轮廓
        shadowOpacity: 0, // 去掉阴影
    },
    slider_wrap: {
        flexDirection: "row",
        alignItems: "center",
    },
    slider_input: {
        width: 56,
        height: 32,
        textAlign: "center",
        borderRadius: 8,
        backgroundColor: '#F1F2F4'
    },
    slider_txt: {
        marginLeft: 8,
        fontSize: 14,
        color: 'rgba(0,0,0,0.5)'
    },
    hotKeyword_wrap: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        height: 48,
        paddingHorizontal: 16
    },
    hotKeyword_left: {
        flexDirection: "row",
        alignItems: "center",
        flex: 1
    },
    hotKeyword_index: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)',
        marginRight: 16,
        fontWeight: 'bold'
    },
    hotKeyword_title: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)',
    },
    hotKeyword_tj: {
        fontSize: 12,
        color: 'rgba(0, 0, 0, 0.3)',
        marginLeft: 16
    },
})